package com.beiye.drivertransport.SubActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.frame.view.linearlistview.LinearListView;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.Video.JZMediaIjk;
import com.beiye.drivertransport.Video.MyJZVideoPlayerStandard;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.adapter.CourseDetailSubjectApt;
import com.beiye.drivertransport.bean.CourseDetailBean;
import com.beiye.drivertransport.bean.CourseDetailSubjectBean;
import com.beiye.drivertransport.bean.LearnphotoBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.SignBean;
import com.beiye.drivertransport.config.AppInterfaceConfig;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.thirdparty.tbs.SuperFileView2;
import com.beiye.drivertransport.utils.FileParseUtil;
import com.beiye.drivertransport.utils.HelpUtil;
import com.beiye.drivertransport.utils.ImageJavascriptInterface;
import com.beiye.drivertransport.utils.JSImgUtil;
import com.beiye.drivertransport.utils.LogUtils;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.beiye.drivertransport.view.CircularProgressView;
import com.githang.statusbar.StatusBarCompat;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.squareup.picasso.Picasso;

import net.frakbot.jumpingbeans.JumpingBeans;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;


import butterknife.OnClick;
import cn.jzvd.JZDataSource;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
import es.dmoral.toasty.Toasty;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

//违章学习界面
public class IllegallearningCourseDetailsActivity extends TwoBaseAty implements SurfaceHolder.Callback {


    WebView web;

    LinearLayout le_parement;

    ImageView img_Courseback;

    ImageView img_course2;

    LinearListView lv_coursedetail;

    MyJZVideoPlayerStandard jcVideoPlayerStandard;

    TextView tv_courseName;


    TextView tv_courseLength;

    LinearLayout le_course;//隐藏照片

    TextView tv_course11;//请回答
    //    @Bind(R.id.tv_course3)
//    Chronometer tv_cumulativeLength;//累计时长

    TextView tv_cumulativeLength;//累计时长


    ImageView show_camera_iv;//显示照片

    ImageView show_camera_iv1;//显示照片

    SurfaceView surfaceSv;//预览照片

    TextView tv_sure;

    TextView tv_courseSave;

    RelativeLayout re_course;//隐藏按钮
    //    @Bind(R.id.re_course1)
//    RelativeLayout re_course1;//照片布局

    TextView img_course;


    SuperFileView2 mSuperFileView;
    private JumpingBeans jumpingBeans2;
    private PopupWindow mDownloadPopWindow;

    private TextView mOffTextView;
    private static final String TAG = IllegallearningCourseDetailsActivity.class.getSimpleName();
    private static final int MEDIA_TYPE_IMAGE = 1;
    private Timer mOffTime;
    private Integer tcsn;
    private boolean isloob=true;
    private long mRecordTime;
    private TimerTask timerTask;

    private Handler mOffHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what > 0) {
                ////动态显示倒计时
                downtime.setText(msg.what+"");
            } else {
                ////倒计时结束自动关闭
                if (mPopWindow != null) {
                    downtime.setVisibility(View.GONE);
                    tv_photo.setText("请拍照，继续学习！");
                    tv_photo4.setVisibility(View.GONE);
                    tv_photo1.setText("你未在规定时间内操作");
                    tv_photo.setTextColor(Color.parseColor("#ff8092"));
                    tv_photo2.setVisibility(View.GONE);
                    img_photo.setImageResource(R.mipmap.sorry);
                    //   mPopWindow.dismiss();
                  //  timerTask.cancel();
                }
                // off();////关闭后的操作
                mOffTime.cancel();
            }
            super.handleMessage(msg);
        }
    };


    private int formattimecnt;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what == 0) {
                ////打开界面时累计时长
//                tv_cumulativeLength.setBase(SystemClock.elapsedRealtime());
//                int hour = (int) ((SystemClock.elapsedRealtime() - tv_cumulativeLength.getBase()) / 1000 / 60);
//                tv_cumulativeLength.setFormat("0" + String.valueOf(hour) + ":%s");
//                tv_cumulativeLength.start();
//                tv_cumulativeLength.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
//
//
//                    @Override
//                    public void onChronometerTick(Chronometer chronometer) {
//                        String format = chronometer.getText().toString();
//
//                        SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
//                                Context.MODE_PRIVATE);
//                        SharedPreferences.Editor edit = sp.edit();
//                        edit.putString("format", format);
//                        edit.commit();
//                        String duration = sp.getString("duration", "");
//                        LogUtils.e("format", format);
//                        LogUtils.e("duration", duration);
//                        if (format.equals(duration)) {
//
//                            tv_cumulativeLength.stop();
//
//                            mRecordTime = SystemClock.elapsedRealtime();
//
//                            Intent  intent= new Intent(SpecifiedLearningCourseDetailsActivity.this,TakePictureActivity.class);
//                            startActivityForResult(intent, 0);
//                         //   initDialog();
//                        }
//                    }
//                });

                SharedPreferences sp1 = getSharedPreferences("IllegallearningCourseDetailsActivity",
                        Context.MODE_PRIVATE);

                String format = sp1.getString("format", "");
                if (format.equals("")) {
                    timerTask = new TimerTask() {
                        int cnt = hadReadLength;

                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    LogUtils.e("测试", "format为空: "+cnt+"  "+ courseLength*60 );
                                    String stringTime = getStringTime(cnt++);
                                    tv_cumulativeLength.setText(stringTime);
                                    SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                            Context.MODE_PRIVATE);
                                    String firsttimestr = getStringTime(firsttime);
                                    SharedPreferences.Editor edit = sp.edit();
                                    edit.putString("format", stringTime);
                                    edit.putString("firsttime", firsttimestr);
                                    edit.commit();
                                    LogUtils.e("format", stringTime);
                                    LogUtils.e("firsttime1", firsttimestr);
                                    //         LogUtils.e("duration", duration);


                                    if (stringTime.equals(firsttimestr)) {
                                        timerTask.cancel();
                                        initDialog();
                                    }
                                    if (cnt > courseLength*60 ) {
                                        timerTask.cancel();
                                        tv_cumulativeLength.setText(getStringTime( courseLength*60));
                                    }
                                }
                            });
                        }
                    };
                    timer1.schedule(timerTask, 0, 1000);
                }else {
                    String[] splitformat = format.split(":");
                    String format1 = splitformat[0];
                    String format2 = splitformat[1];
                    String format3 = splitformat[2];
                    int iformat1 = Integer.valueOf(format1);//转int
                    int iformat2 = Integer.valueOf(format2);//转int
                    int iformat3 = Integer.valueOf(format3);//转int
                    int formattime = iformat1 * 3600 + iformat2 * 60 + iformat3 * 1;
                    formattimecnt = formattime;
                    timerTask = new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    LogUtils.e("测试", "format非空: "+formattimecnt+"  "+ courseLength*60 );

                                    String stringTime = getStringTime(formattimecnt++);
                                    tv_cumulativeLength.setText(stringTime);

                                    SharedPreferences sp1 = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                            Context.MODE_PRIVATE);
                                    String firsttimestr1 = getStringTime(firsttime1);
                                    LogUtils.e("format", stringTime);
                                    LogUtils.e("firsttime1", firsttimestr1);
                                    SharedPreferences.Editor edit = sp1.edit();
                                    edit.putString("format", stringTime);
                                    edit.putString("firsttime", firsttimestr1);
                                    edit.commit();

                                    String imgurl = sp1.getString("imgurl", "");
                                    if (imgurl.equals("")) {
                                        if (stringTime.equals(firsttimestr1)) {
                                            timerTask.cancel();
                                            //tv_pause.setVisibility(View.GONE);
                                            initDialog();
                                        }
                                    } else {
                                        int courseLength = sp1.getInt("courseLength", 0);
                                        int courseLengthtime = courseLength * 60;
                                        String courseLengthtime1 = getStringTime(courseLengthtime);
                                        LogUtils.e("退出拍照后计时", stringTime);
                                        if (stringTime.equals(courseLengthtime1)) {
                                            timerTask.cancel();
                                        }
                                    }

                                    if (formattimecnt >  courseLength*60 ) {
                                        timerTask.cancel();
                                        tv_cumulativeLength.setText(getStringTime(courseLength*60));
                                    }

                                }
                            });
                        }
                    };
                    timer1.schedule(timerTask, 0, 1000);
                }
            }
//            else if (what == 1) {
//                WebSettings settings = web.getSettings();
//                // 允许使用脚本语言
//                settings.setJavaScriptEnabled(true);
//                // 支持缩放
//                settings.setSupportZoom(true);
//                //  mWebView.addJavascriptInterface(new JavaScriptinterface(BannerItemAty.this), "android");
//
//                // 在当前应用加载网页(直接加载网页不经过浏览器）
//                web.setWebViewClient(new WebViewClient() {
//                    @Override // 开始加载网页时触发
//                    public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                        super.onPageStarted(view, url, favicon);
//
//                    }
//
//                    @Override // 网页加载完成之后触发
//                    public void onPageFinished(WebView view, String url) {
//
//                        super.onPageFinished(view, url);
//
//                    }
//                });
//
//                web.loadUrl(AppInterfaceConfig.BASE_URL + "app/course/content?" + "sn=" + tcsn);
//
//                // 显示进度
//                web.setWebChromeClient(new WebChromeClient() {
//                    @Override // 加载网页进度改变时触发
//                    public void onProgressChanged(WebView view, int newProgress) {
//
//                        super.onProgressChanged(view, newProgress);
//                    }
//                });
//            }
        }
    };
    private CourseDetailSubjectApt courseDetailSubjectApt;
    private Camera mCamera;
    private SurfaceHolder mHolder;
    private PopupWindow mPopWindow;
    private PopupWindow showBigPw;
    private long rangeTime;
    private FileInputStream fStream;
    private List<CourseDetailSubjectBean.RowsBean> rowsList;
    private int readInterval;
    private String orgId;
    private int otcSn;
    private Timer timer1;

    private int firsttime;

    private int subformatTurnSecond;
    private SensorManager sensorManager;
    private Jzvd.JZAutoFullscreenListener sensorEventListener;
    private int minPer;
    private TextView downtime;
    private PopupWindow mSorryPopWindow;
    //  private CustomProgressDialog mdialog;
    private ProgressDialog mProgressDialog;
    private int sn;
    private int firsttime1;
    private PopupWindow mPopWindow2;
    private TextView tv_photo2;
    private TextView tv_photo4;
    private TextView tv_photo1;
    private TextView tv_photo;
    private ImageView img_photo;
    private int hadReadLength=0;
    private int courseLength;


    @Override
    public int getLayoutId() {
        return R.layout.activity_illegallearning_course_details;
    }

    private String getStringTime(int cnt) {
        int hour = cnt/3600;
        int min = cnt % 3600 / 60;
        int second = cnt % 60;
        return String.format(Locale.CHINA,"%02d:%02d:%02d",hour,min,second);
    }
    private String getNumTime(int cnt) {
        int hour = cnt/3600;
        int min = cnt % 3600 / 60;
        int second = cnt % 60;
        if(hour==0)
        {

            return String.format(Locale.CHINA,"%02d分%02d秒",min,second);
        }else{

            return String.format(Locale.CHINA,"%02d小时%02d分%02d秒",hour,min,second);
        }
    }


    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ac_coursedown_tv_save) {
            if (Jzvd.backPress()) {
                return;
            }
            exitAndSave();
        } else if (id == R.id.img_Courseback) {
            if (Jzvd.backPress()) {
                return;
            }
            exitAndSave();
                /*TiShiDialog.Builder builder = new TiShiDialog.Builder(this);
                builder.setMessage("点放弃,将自动放弃本课程学习记录");
                builder.setTitle("提示:");
                builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                Context.MODE_PRIVATE);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.clear();
                        edit.commit();
                        timerTask.cancel();
                        timer1.cancel();
                        timerTask=null;
                        timer1=null;
                        dialog.dismiss();
                        finish();
                        //设置你的操作事项
                    }
                });

                builder.setNegativeButton("取消",
                        new android.content.DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                builder.create().show();*/
        } else if (id == R.id.tv_course10) {//提交
            if (Utils.isFastClicker()) {
                return;
            }
            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                    Context.MODE_PRIVATE);
            String format = sp.getString("format", "");
            String imgurl = sp.getString("imgurl", "");
            int num = sp.getInt("num", 0);
            String[] splitformat = format.split(":");
            String format1 = splitformat[0];
            String format2 = splitformat[1];
            String format3 = splitformat[2];
            int iformat1 = Integer.valueOf(format1);//转int
            int iformat2 = Integer.valueOf(format2);//转int
            int iformat3 = Integer.valueOf(format3);//转int
            int formattime = iformat1 * 3600 + iformat2 * 60 + iformat3 * 1;


            if (formattime < num) { //学习时间小于总时长
                // String numTime = getNumTime(num);
                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                builder1.setMessage("学习时间不足，不能提交。");
                builder1.setTitle("提示:");
                builder1.setPositiveButton("继续学习", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //设置你的操作事项
                    }
                });
                builder1.create().show();
                //userViolationTCourseFinish(sn,formattime,0);
            } else {
                if (imgurl.equals("")) {
                    timerTask.cancel();
                    //  tv_pause.setVisibility(View.GONE);
                    initDialog2();
                    return;
                }

                if (rowsList.size() != 0) { //课后系统判断
                    for (int i = 0; i < rowsList.size(); i++) {
                        if (rowsList.get(i).isSelect() == false) {
                            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                            builder1.setMessage("第" + (i + 1) + "测验题未答，请答题");
                            builder1.setTitle("提示:");
                            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    //设置你的操作事项
                                }
                            });
                            builder1.create().show();
                            return;
                        } else {
                            if (rowsList.get(i).isLOOP() == false) {
                                TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
                                builder1.setMessage("第" + (i + 1) + "测验题回答错误，请重新答题");
                                builder1.setTitle("提示:");
                                builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        //设置你的操作事项
                                    }
                                });
                                builder1.create().show();
                                return;
                            }
                        }
                    }

                    mProgressDialog = new ProgressDialog(IllegallearningCourseDetailsActivity.this, ProgressDialog.THEME_HOLO_DARK);
                    mProgressDialog.setMessage("保存中...");
                    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.show();
//                        mdialog = CustomProgressDialog.show(SpecifiedLearningCourseDetailsActivity.this, "提交中...", false, null);
                    //有题目调提交接口
                    userViolationTCourseFinish(sn, num, 1);
                       /* if(imgurl.equals(""))
                        {
                            timerTask.cancel();
                            //  tv_pause.setVisibility(View.GONE);
                            initDialog2();
                            return;
                        }
                        mProgressDialog = new ProgressDialog(IllegallearningCourseDetailsActivity.this,ProgressDialog.THEME_HOLO_DARK);
                        mProgressDialog.setMessage("提交中...");
                        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        mProgressDialog.setCancelable(false);
                        mProgressDialog.show();
//                        mdialog = CustomProgressDialog.show(SpecifiedLearningCourseDetailsActivity.this, "提交中...", false, null);
                        //提交违章学习
                        OkGo.get(AppInterfaceConfig.BASE_URL+"course/userViolationTCourse/finish/"+sn)
                                .tag(this)
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String result, Call call, Response response) {
                                        SignBean signBean = JSON.parseObject(result, SignBean.class);
                                        SignBean.DataBean data = signBean.getData();
                                        if(data.getUvtfinishMark()==0)//未完成
                                        {
                                            timerTask.cancel();
                                            timer1.cancel();
                                            timerTask=null;
                                            timer1=null;

                                            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                                    Context.MODE_PRIVATE);
                                            SharedPreferences.Editor edit = sp.edit();
                                            edit.clear();
                                            edit.commit();
                                            mProgressDialog.dismiss();
                                            finish();
                                            showToast("该课程提交成功");

                                        }else if( data.getUvtfinishMark()==1)//已完成未签名
                                        {
                                            timerTask.cancel();
                                            timer1.cancel();
                                            timerTask=null;
                                            timer1=null;

                                            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                                    Context.MODE_PRIVATE);
                                            SharedPreferences.Editor edit = sp.edit();
                                            edit.clear();
                                            edit.commit();
                                            int uvtSn = data.getUvtSn();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("sn", uvtSn);
                                            bundle.putString("signPicUrl", "");
                                            startActivity(SignillegallearningActivity.class, bundle);
                                            mProgressDialog.dismiss();
                                            finish();
                                            showToast("该课程提交成功");
                                        }else   if(data.getUvtfinishMark()==2) {
                                            timerTask.cancel();
                                            timer1.cancel();
                                            timerTask=null;
                                            timer1=null;

                                            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                                    Context.MODE_PRIVATE);
                                            SharedPreferences.Editor edit = sp.edit();
                                            edit.clear();
                                            edit.commit();
                                            mProgressDialog.dismiss();
                                            finish();
                                            showToast("该课程提交成功");

                                        }



                                    }

                                    @Override
                                    public void onError(Call call, Response response, Exception e) {
                                        super.onError(call, response, e);
                                        mProgressDialog.dismiss();
                                        String message = e.getMessage();
                                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(IllegallearningCourseDetailsActivity.this);
                                        builder1.setMessage(message);
                                        builder1.setTitle("提示:");
                                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                                //设置你的操作事项
                                            }
                                        });

                                        builder1.create().show();

                                    }
                                });*/
                } else {//没有题目调提交接口
                    mProgressDialog = new ProgressDialog(IllegallearningCourseDetailsActivity.this, ProgressDialog.THEME_HOLO_DARK);
                    mProgressDialog.setMessage("保存中...");
                    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.show();
                    userViolationTCourseFinish(sn, num, 1);
                        /*if(imgurl.equals(""))
                        {
                            timerTask.cancel();
                            initDialog2();
                            return;
                        }
                        mProgressDialog = new ProgressDialog(IllegallearningCourseDetailsActivity.this,ProgressDialog.THEME_HOLO_DARK);
                        mProgressDialog.setMessage("提交中...");
                        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        mProgressDialog.setCancelable(false);
                        mProgressDialog.show();
//                        mdialog = CustomProgressDialog.show(SpecifiedLearningCourseDetailsActivity.this, "提交中...", false, null);
                        //提交违章学习
                        OkGo.get(AppInterfaceConfig.BASE_URL+"course/userViolationTCourse/finish/"+sn)
                                .tag(this)
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String result, Call call, Response response) {
                                        SignBean signBean = JSON.parseObject(result, SignBean.class);
                                        SignBean.DataBean data = signBean.getData();
                                        if(data.getUvtfinishMark()==0)//未完成
                                        {
                                            timerTask.cancel();
                                            timer1.cancel();
                                            timerTask=null;
                                            timer1=null;

                                            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                                    Context.MODE_PRIVATE);
                                            SharedPreferences.Editor edit = sp.edit();
                                            edit.clear();
                                            edit.commit();
                                            mProgressDialog.dismiss();
                                            finish();
                                            showToast("该课程提交成功");

                                        }else if( data.getUvtfinishMark()==1)//已完成未签名
                                        {
                                            timerTask.cancel();
                                            timer1.cancel();
                                            timerTask=null;
                                            timer1=null;

                                            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                                    Context.MODE_PRIVATE);
                                            SharedPreferences.Editor edit = sp.edit();
                                            edit.clear();
                                            edit.commit();
                                            int uvtSn = data.getUvtSn();
                                            Bundle bundle = new Bundle();
                                            bundle.putInt("sn", uvtSn);
                                            bundle.putString("signPicUrl", "");
                                            startActivity(SignillegallearningActivity.class, bundle);
                                            mProgressDialog.dismiss();
                                            finish();
                                            showToast("该课程提交成功");
                                        }else if(data.getUvtfinishMark()==2) {
                                            timerTask.cancel();
                                            timer1.cancel();
                                            timerTask=null;
                                            timer1=null;

                                            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                                    Context.MODE_PRIVATE);
                                            SharedPreferences.Editor edit = sp.edit();
                                            edit.clear();
                                            edit.commit();
                                            mProgressDialog.dismiss();
                                            finish();
                                            showToast("该课程提交成功");

                                        }



                                    }

                                    @Override
                                    public void onError(Call call, Response response, Exception e) {
                                        super.onError(call, response, e);
                                        mProgressDialog.dismiss();
                                        String message = e.getMessage();
                                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(IllegallearningCourseDetailsActivity.this);
                                        builder1.setMessage(message);
                                        builder1.setTitle("提示:");
                                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                                //设置你的操作事项
                                            }
                                        });

                                        builder1.create().show();
                                    }
                                });*/
                }

            }
        } else if (id == R.id.img_course1) {
            if (!isloob) {
                img_course.setText("展开拍照");
                le_course.setVisibility(View.GONE);
                img_course2.setImageResource(R.mipmap.down3);
                isloob = true;
            } else {
                img_course.setText("收起拍照");
                le_course.setVisibility(View.VISIBLE);
                img_course2.setImageResource(R.mipmap.top3);
                isloob = false;
            }
        }
    }

    @Override
    public void onSuccess(String result, Call call, Response response, int what) {
        super.onSuccess(result, call, response, what);
        if(what==1){
            SignBean signBean = JSON.parseObject(result, SignBean.class);
            SignBean.DataBean data = signBean.getData();
            if(data.getUvtfinishMark()==0)//未完成
            {
                timerTask.cancel();
                timer1.cancel();
                timerTask=null;
                timer1=null;

                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                mProgressDialog.dismiss();
                showToast("该课程保存成功");
                finish();

            }else if( data.getUvtfinishMark()==1)//已完成未签名
            {
                timerTask.cancel();
                timer1.cancel();
                timerTask=null;
                timer1=null;

                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                int uvtSn = data.getUvtSn();
                Bundle bundle = new Bundle();
                bundle.putInt("sn", uvtSn);
                bundle.putString("signPicUrl", "");
                startActivity(SignillegallearningActivity.class, bundle);
                mProgressDialog.dismiss();
                showToast("该课程提交成功");
                finish();
            }else   if(data.getUvtfinishMark()==2) {
                timerTask.cancel();
                timer1.cancel();
                timerTask=null;
                timer1=null;

                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                mProgressDialog.dismiss();
                showToast("该课程提交成功");
                finish();
            }
        }
    }

    @Override
    public void initData() {
        web = (WebView) findViewById(R.id.wb_course);
        le_parement = (LinearLayout) findViewById(R.id.le_couse);
        img_Courseback = (ImageView) findViewById(R.id.img_Courseback);
        img_course2 = (ImageView) findViewById(R.id.img_course2);
        lv_coursedetail = (LinearListView) findViewById(R.id.lv_coursedetail);
        jcVideoPlayerStandard = (MyJZVideoPlayerStandard) findViewById(R.id.videoplayer);
        tv_courseName = (TextView) findViewById(R.id.tv_course);
        tv_courseLength = (TextView) findViewById(R.id.tv_course2);
        le_course = (LinearLayout)findViewById(R.id.le_course);
        tv_course11 = (TextView)findViewById(R.id.tv_course11);
        tv_cumulativeLength = (TextView)findViewById(R.id.tv_course3);
        show_camera_iv = (ImageView)findViewById(R.id.id_show_camera_iv);
        show_camera_iv1 = (ImageView)findViewById(R.id.id_show_camera_iv1);
        surfaceSv = (SurfaceView)findViewById(R.id.id_area_sv);
        tv_sure = (TextView) findViewById(R.id.tv_course10);
        tv_courseSave = (TextView) findViewById(R.id.ac_coursedown_tv_save);
        re_course = (RelativeLayout)findViewById(R.id.re_course);
        img_course = (TextView) findViewById(R.id.img_course1);
        mSuperFileView = (SuperFileView2) findViewById(R.id.mSuperFileView);

        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        //注册EventBus
        EventBus.getDefault().register(this);

        web.getSettings().setJavaScriptEnabled(true);
        web.getSettings().setSavePassword(false);
        web.getSettings().setSaveFormData(false);
        web.removeJavascriptInterface("accessibility");
        web.removeJavascriptInterface("accessibilityTraversal");
        web.getSettings().setAllowFileAccessFromFileURLs(false);
        web.setHorizontalScrollBarEnabled(false);//水平不显示
        web.setVerticalScrollBarEnabled(false); //垂直不显示
        web.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView  view, String url) {
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                JSImgUtil.setWebImageClick(view,JSImgUtil.JSCALLJAVA);
                super.onPageFinished(view, url);
            }
        });

        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensorEventListener = new Jzvd.JZAutoFullscreenListener();
        Sensor accelerometerSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(sensorEventListener, accelerometerSensor, SensorManager.SENSOR_DELAY_NORMAL);

        show_camera_iv.setImageResource(R.mipmap.tongming);
        timer1 = new Timer();

        firsttime = (int)(20+Math.random()*(30-20+1));//第一次拍照随机20秒到30秒
        //firsttime=3;
        //第二次验证拍照一分钟之后随机20秒到30秒
        firsttime1 = (int) (80 + Math.random() * (30 - 20 + 1));
        Bundle bundle = getIntent().getExtras();
        //通过name关键字取出用户名
        tcsn = bundle.getInt("tcsn");
        minPer = bundle.getInt("minPer");
        sn = bundle.getInt("sn");
        hadReadLength=bundle.getInt("havedLength");

        LogUtils.e("测试", "initData: "+sn +' '+tcsn);
        getUserPhoto(sn);


//        Thread thread1 = new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
//                mHandler.sendEmptyMessage(1);
//            }
//        });
//        thread1.start();
        //摄像头
        int cameraCount = 1;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();// 得到摄像头的个数

        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);// 得到每一个摄像头的信息
            // 现在是后置，变更为前置
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                /**
                 * 记得释放camera，方便其他应用调用
                 */
                releaseCamera();
                // 打开当前选中的摄像头
                mCamera = Camera.open(i);
                //   mCamera.setDisplayOrientation(90);//旋转度数
                // 通过surfaceview显示取景画面
                setStartPreview(mCamera, mHolder);

            }
        }
        // 获得句柄
        mHolder = surfaceSv.getHolder();
        // 添加回调
        mHolder.addCallback(this);

    }



//    @Override
//    public void onSuccess(String result, Call call, Response response, int what) {
//        if(what==3)
//        {
//            SignBean signBean = JSON.parseObject(result, SignBean.class);
//            SignBean.DataBean data = signBean.getData();
//            if(data.getUvtfinishMark()==0)//未完成
//            {
//                timer1.cancel();
////                SharedPreferences spp = getSharedPreferences("imgurl",
////                        Context.MODE_PRIVATE);
////                SharedPreferences.Editor editor = spp.edit();
////                editor.clear();
////                editor.commit();
//                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
//                        Context.MODE_PRIVATE);
//                SharedPreferences.Editor edit = sp.edit();
//                edit.clear();
//                edit.commit();
//                mProgressDialog.dismiss();
//                finish();
//                showToast("该课程提交成功");
//
//            }else if( data.getUvtfinishMark()==1)//已完成未签名
//            {
//                timer1.cancel();
////                SharedPreferences spp = getSharedPreferences("imgurl",
////                        Context.MODE_PRIVATE);
////                SharedPreferences.Editor editor = spp.edit();
////                editor.clear();
////                editor.commit();
//                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
//                        Context.MODE_PRIVATE);
//                SharedPreferences.Editor edit = sp.edit();
//                edit.clear();
//                edit.commit();
//                int uvtSn = data.getUvtSn();
//                Bundle bundle = new Bundle();
//                bundle.putInt("sn", uvtSn);
//                bundle.putString("signPicUrl", "");
//                startActivity(SignillegallearningActivity.class, bundle);
//                mProgressDialog.dismiss();
//                finish();
//                showToast("该课程提交成功");
//            }
//        }
//
//        super.onSuccess(result, call, response, what);
//    }
//    @Override
//    public void onError(String result, Call call, Response response, int what) {
//        if(what==3)
//        {
//            mProgressDialog.dismiss();
//            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
//            //     int code = checkBean.getCode();
//            String msg = checkBean.getMsg();
//            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
//            builder1.setMessage(msg);
//            builder1.setTitle("提示:");
//            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();;
//                    //设置你的操作事项
//                }
//            });
//            builder1.create().show();
//
//        }
//
//        super.onError(result, call, response, what);
//    }


    @Override
    public void requestData() {
        initcourseData();
        initcoursesubject();

    }

    private void getUserPhoto(int sn) {
        OkGo.get(AppInterfaceConfig.BASE_URL+"course/userVtcPhoto/findByUvtcSn/"+sn)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {
                        LearnphotoBean learnphotoBean = JSON.parseObject(result, LearnphotoBean.class);
                        List<LearnphotoBean.RowsBean> rows = learnphotoBean.getRows();
                        if(rows.size()>0){
                            String messageurl=rows.get(0).getUrl();
                            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity", Context.MODE_PRIVATE);
                            SharedPreferences.Editor edit = sp.edit();
                            edit.putString("imgurl", messageurl);
                            edit.commit();

                            if (messageurl.contains("aliyuncs.com")) {
                                Picasso.with(IllegallearningCourseDetailsActivity.this).load(Uri.parse(messageurl)).placeholder(R.mipmap.no_data).into(show_camera_iv);
                            } else {
                                Picasso.with(IllegallearningCourseDetailsActivity.this).load(Uri.parse(AppInterfaceConfig.getRequestUrl(messageurl))).placeholder(R.mipmap.no_data).into(show_camera_iv);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        String message = e.getMessage();
                        TiShiDialog.Builder builder1 = new TiShiDialog.Builder(IllegallearningCourseDetailsActivity.this);
                        builder1.setMessage(message);
                        builder1.setTitle("提示:");
                        builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                //设置你的操作事项
                            }
                        });

                        builder1.create().show();



                    }
                });
    }

    //根据课程序列号查询测验题
    private void initcoursesubject() {
        OkGo.get(AppInterfaceConfig.BASE_URL + "course/question/" + tcsn)     // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {
                        CourseDetailSubjectBean courseDetailSubjectBean = JSON.parseObject(result, CourseDetailSubjectBean.class);
                        rowsList = courseDetailSubjectBean.getRows();
                        if(rowsList.size()==0)
                        {
                            tv_course11.setVisibility(View.GONE);
                            return;
                        }
                        tv_course11.setVisibility(View.VISIBLE);
                        courseDetailSubjectApt = new CourseDetailSubjectApt(IllegallearningCourseDetailsActivity.this, rowsList, R.layout.course_detail_item);
                        lv_coursedetail.setAdapter(courseDetailSubjectApt);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        showToast("网络连接错误");
                    }
                });
    }

    //根据课程序列号查询课程详情
    private void initcourseData() {
        OkGo.get(AppInterfaceConfig.BASE_URL + "course/course/" + tcsn)     // 请求方式和请求url
                .tag(this)                       // 请求的 tag, 主要用于取消对应的请求
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String result, Call call, Response response) {

                        CourseDetailBean courseDetailBean = JSON.parseObject(result, CourseDetailBean.class);
                        CourseDetailBean.DataBean coursedata = courseDetailBean.getData();


                        String courseName = coursedata.getCourseName();//课程名称
                        if(courseName==null)
                        {
                            return;
                        }


                        //课程时长
                        courseLength = coursedata.getCourseLength();
                        Thread thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                                mHandler.sendEmptyMessage(0);
                            }
                        });
                        thread.start();
                        SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                                Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        //    editor.putString("duration", duration);
                        editor.putInt("courseLength", courseLength);
                        editor.commit();

                        LogUtils.e("测试", "onSuccess: "+courseLength );

                        tv_courseName.setText(courseName);
                        tv_courseLength.setText("课程时长:" + courseLength + "分钟");
                        //视频地址
                        String accessVideoUrl = coursedata.getAccessVideoUrl();

                        video(accessVideoUrl);
                        if(courseLength ==0)
                        {
                            return;
                        }
                        //课长判断何久拍照
                        photo(courseLength);
                        String courseContent = coursedata.getCourseContent();


                        if(courseContent!=null)
                        {
                            String[] imgs = JSImgUtil.returnImageUrlsFromHtml(coursedata.getCourseContent());
                            if(imgs!=null){
                                web.addJavascriptInterface(new ImageJavascriptInterface(IllegallearningCourseDetailsActivity.this,imgs), JSImgUtil.JSCALLJAVA);
                            }
                            new Thread(new runn(courseContent)).start();
                        }

                        //PDF文件解析
                        String fileUrl = coursedata.getFileUrl();
                        String fileName = coursedata.getFileName();
                        if (fileUrl != null) {
                            mSuperFileView.setVisibility(View.VISIBLE);
                            mSuperFileView.setOnGetFilePathListener(new SuperFileView2.OnGetFilePathListener() {
                                @Override
                                public void onGetFilePath(SuperFileView2 mSuperFileView2) {
                                    String path = FileParseUtil.getFilePath(mSuperFileView2, fileUrl, fileName);
                                    if (path.contains("http")) {//网络地址要先下载
                                        showAlertDialog(mSuperFileView2, fileUrl);
                                    } else {
                                        mSuperFileView2.displayFile(new File(path));
                                    }
                                }
                            });
                            mSuperFileView.show();
                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        showToast("网络连接错误");
                    }
                });
    }
    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
            element.attr("width", "100%").attr("height", "auto");
        }

        return doc.toString();
    }
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("value");
            String html = "<html><body>" + val + "</body></html>";
            web.loadDataWithBaseURL(null,
                    getNewContent(html), "text/html", "utf-8",
                    null);
        }
    };
    /**
     * 网络操作相关的子线程
     */
    public class runn implements Runnable {
        String vv;

        public runn(String vv) {
            this.vv = vv;
        }

        @Override
        public void run() {
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("value", vv);
            msg.setData(data);
            handler.sendMessage(msg);
        }
    }
    private void photo(int courseLength) {
        LoginUserBean userInfo = UserManger.getUserInfo();
//        Integer minPer = userInfo.getMinPer();//所属行政区划学习时长最低百分比
        int num = (courseLength * 60 * minPer) / 100;
//        Random rand = new Random();
//        int i = rand.nextInt(num);
//        int j = i + 1;
//        int j = (int) (num * 0.35 + Math.random() * (num * 0.45 - num * 0.35 + 1));//第二次拍照随机
//
//        TimeUtils timeUtils = new TimeUtils();
//        String duration = timeUtils.stringForTime(j * 1000);
        SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        //    editor.putString("duration", duration);
        editor.putInt("num", num);
        editor.commit();


    }


    private void video(String accessVideoUrl) {
        if (accessVideoUrl == null) {
            jcVideoPlayerStandard.setVisibility(View.GONE);
            return;
        }

        jcVideoPlayerStandard.setVisibility(View.VISIBLE);
        HashMap headers = new HashMap<String, String>();
        headers.put("Referer",AppInterfaceConfig.BASE_URL);
        JZDataSource jzDataSource=new JZDataSource(accessVideoUrl,"",headers);
        jcVideoPlayerStandard.setUp(jzDataSource,jcVideoPlayerStandard.SCREEN_NORMAL);
        //jcVideoPlayerStandard.setUp(accessVideoUrl,"", jcVideoPlayerStandard.SCREEN_NORMAL, JZMediaIjk.class);
    //    jcVideoPlayerStandard.startVideo();//自动播放
        Picasso.with(getApplicationContext()).load(R.mipmap.video)
                .into(jcVideoPlayerStandard.thumbImageView);
       // JZVideoPlayer.setJzUserAction(new MyUserActionStandard());
        JzvdStd.progressBar.setEnabled(false);//禁止拖动
    }

    /**
     * 这只是给埋点统计用户数据用的，不能写和播放相关的逻辑，监听事件请参考MyJZVideoPlayerStandard，复写函数取得相应事件
     */
//    class MyUserActionStandard implements JZUserActionStandard {
//
//        @Override
//        public void onEvent(int type, Object url, int screen, Object... objects) {
//            switch (type) {
//                case JZUserAction.ON_CLICK_START_ICON:
//                    Log.i("USER_EVENT", "ON_CLICK_START_ICON" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_CLICK_START_ERROR:
//                    Log.i("USER_EVENT", "ON_CLICK_START_ERROR" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_CLICK_START_AUTO_COMPLETE:
//                    Log.i("USER_EVENT", "ON_CLICK_START_AUTO_COMPLETE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_CLICK_PAUSE:
//                    Log.i("USER_EVENT", "ON_CLICK_PAUSE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_CLICK_RESUME:
//                    Log.i("USER_EVENT", "ON_CLICK_RESUME" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_SEEK_POSITION:
//                    Log.i("USER_EVENT", "ON_SEEK_POSITION" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_AUTO_COMPLETE:
//                    Log.i("USER_EVENT", "ON_AUTO_COMPLETE" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_ENTER_FULLSCREEN:
//                    Log.i("USER_EVENT", "ON_ENTER_FULLSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_QUIT_FULLSCREEN:
//                    Log.i("USER_EVENT", "ON_QUIT_FULLSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_ENTER_TINYSCREEN:
//                    Log.i("USER_EVENT", "ON_ENTER_TINYSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_QUIT_TINYSCREEN:
//                    Log.i("USER_EVENT", "ON_QUIT_TINYSCREEN" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_TOUCH_SCREEN_SEEK_VOLUME:
//                    Log.i("USER_EVENT", "ON_TOUCH_SCREEN_SEEK_VOLUME" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserAction.ON_TOUCH_SCREEN_SEEK_POSITION:
//                    Log.i("USER_EVENT", "ON_TOUCH_SCREEN_SEEK_POSITION" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//
//                case JZUserActionStandard.ON_CLICK_START_THUMB:
//                    Log.i("USER_EVENT", "ON_CLICK_START_THUMB" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                case JZUserActionStandard.ON_CLICK_BLANK:
//                    Log.i("USER_EVENT", "ON_CLICK_BLANK" + " title is : " + (objects.length == 0 ? "" : objects[0]) + " url is : " + url + " screen is : " + screen);
//                    break;
//                default:
//                    Log.i("USER_EVENT", "unknow");
//                    break;
//            }
//        }
//    }



    @SuppressLint("HandlerLeak")
    private void initDialog() {
        //设置contentView
        View contentView = LayoutInflater.from(IllegallearningCourseDetailsActivity.this).inflate(R.layout.course_popwindowlayout, null);
        mPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);

        //倒计时
        downtime = (TextView)contentView.findViewById(R.id.tv_photo3);
        tv_photo2 = (TextView)contentView.findViewById(R.id.tv_photo2);
        tv_photo4 = (TextView)contentView.findViewById(R.id.tv_photo4);
        tv_photo1 = (TextView)contentView.findViewById(R.id.tv_photo1);
        tv_photo = (TextView)contentView.findViewById(R.id.tv_photo);
        img_photo = (ImageView)contentView.findViewById(R.id.img_photo);
        TextPaint paint = downtime.getPaint();
        paint.setFakeBoldText(true);//字体加粗
        ImageView takepciture = (ImageView)contentView.findViewById(R.id.img_photo1);//点拍照
        //    LinearLayout le_takepicture = (LinearLayout)contentView.findViewById(R.id.le_takepicture);//跟布局
        takepciture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mOffTime.cancel();
                timerTask.cancel();
                mPopWindow.dismiss();
                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity", Context.MODE_PRIVATE);
                String firsttime = sp.getString("firsttime", "");//第一次抓拍时间
                String firsttimesub = firsttime.substring(3, 8);//截取字符串00:00:00变成00:00
                LoginUserBean userInfo = UserManger.getUserInfo();
                LoginUserBean.DataBean data = userInfo.getData();
                String userId = data.getUserId();
                Bundle bundle = new Bundle();
                bundle.putInt("uvtSn",sn);
                bundle.putString("snapTime", firsttimesub);
                bundle.putString("userId", userId);
                startActivityForResult(TakePhotoIllegallearningActivity.class,bundle, 0);
            }
        });

//        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                // popupWindow隐藏时恢复屏幕正常透明度
//                setBackgroundAlpha(1.0f);
//            }
//        });
//        setBackgroundAlpha(0.35f);//设置屏幕透明度
//        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setFocusable(false);
        mPopWindow.setOutsideTouchable(false);
        mPopWindow.showAtLocation(le_parement, Gravity.CENTER, 0, 0);
        //////倒计时
        mOffTime = new Timer(true);
        TimerTask tt = new TimerTask() {
            int countTime = 15;

            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = countTime;
                mOffHandler.sendMessage(msg);

            }
        };
        mOffTime.schedule(tt, 1000, 1000);
    }

    @SuppressLint("HandlerLeak")
    private void initDialog2() {

        //设置contentView
        View contentView = LayoutInflater.from(IllegallearningCourseDetailsActivity.this).inflate(R.layout.test_popwindowlayout, null);
        mPopWindow2 = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);


        ImageView takepciture = (ImageView)contentView.findViewById(R.id.img_photo1);//点拍照
        LinearLayout le_takepicture = (LinearLayout)contentView.findViewById(R.id.le_takepicture1);//跟布局
        takepciture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mPopWindow2.dismiss();
                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                        Context.MODE_PRIVATE);
                String firsttime = sp.getString("firsttime", "");//第一次抓拍时间
                String firsttimesub = firsttime.substring(3, 8);//截取字符串00:00:00变成00:00
                LoginUserBean userInfo = UserManger.getUserInfo();
                LoginUserBean.DataBean data = userInfo.getData();
                if(data==null)
                {
                    return;
                }
                String userId = data.getUserId();
                Bundle bundle = new Bundle();
                bundle.putInt("uvtSn",sn);
                bundle.putString("snapTime", firsttimesub);
                bundle.putString("userId", userId);
                startActivityForResult(TakePhotoIllegallearningActivity.class,bundle, 0);
            }
        });

//        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                // popupWindow隐藏时恢复屏幕正常透明度
//                setBackgroundAlpha(1.0f);
//            }
//        });
//        setBackgroundAlpha(0.35f);//设置屏幕透明度
//        mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow2.setFocusable(false);
        mPopWindow2.setOutsideTouchable(false);
        mPopWindow2.showAtLocation(le_takepicture, Gravity.CENTER, 0, 0);

    }



    @Override
    public boolean dispatchTouchEvent(MotionEvent event){
        if(mPopWindow!=null&&mPopWindow.isShowing()){
            return false;
        }
        if(mSorryPopWindow!=null&&mSorryPopWindow.isShowing()){
            return false;
        }
        if(mPopWindow2!=null&&mPopWindow2.isShowing()){
            return false;
        }
        return super.dispatchTouchEvent(event);
    }

    private void ShowSorryPopwindow() {

        View contentView = LayoutInflater.from(IllegallearningCourseDetailsActivity.this).inflate(R.layout.sorry_popwindowlayout, null);
        mSorryPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        //   LinearLayout le_sorry = (LinearLayout)contentView.findViewById(R.id.le_sorry);//跟布局
        ImageView sorry_exit = (ImageView)contentView.findViewById(R.id.sorry_img_photo1);//退出
        sorry_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSorryPopWindow.dismiss();
                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.remove("format");
                edit.commit();
                Thread thread2 = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                        mHandler.sendEmptyMessage(0);
                    }
                });
                thread2.start();

            }
        });
//        mSorryPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                // popupWindow隐藏时恢复屏幕正常透明度
//                setBackgroundAlpha(1.0f);
//            }
//        });
//        setBackgroundAlpha(0.35f);//设置屏幕透明度
        //      mSorryPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mSorryPopWindow.setFocusable(false);
        mSorryPopWindow.setOutsideTouchable(false);
        mSorryPopWindow.showAtLocation(le_parement, Gravity.CENTER, 0, 0);

    }






    //    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
//        final double ASPECT_TOLERANCE = 0.1;
//        double targetRatio = (double) w / h;
//        if (sizes == null) return null;
//
//        Camera.Size optimalSize = null;
//        double minDiff = Double.MAX_VALUE;
//
//        int targetHeight = h;
//
//        // Try to find an size match aspect ratio and size
//        for (Camera.Size size : sizes) {
//            double ratio = (double) size.width / size.height;
//            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
//            if (Math.abs(size.height - targetHeight) < minDiff) {
//                optimalSize = size;
//                minDiff = Math.abs(size.height - targetHeight);
//            }
//        }
//
//        // Cannot find the one match the aspect ratio, ignore the requirement
//        if (optimalSize == null) {
//            minDiff = Double.MAX_VALUE;
//            for (Camera.Size size : sizes) {
//                if (Math.abs(size.height - targetHeight) < minDiff) {
//                    optimalSize = size;
//                    minDiff = Math.abs(size.height - targetHeight);
//                }
//            }
//        }
//        return optimalSize;
//    }




    //    /**
//     * 设置添加屏幕的背景透明度
//     *
//     * @param bgAlpha
//     *            屏幕透明度0.0-1.0 1表示完全不透明
//     */
//    public void setBackgroundAlpha(float bgAlpha) {
//        WindowManager.LayoutParams lp = (SpecifiedLearningCourseDetailsActivity.this).getWindow()
//                .getAttributes();
//        lp.alpha = bgAlpha;
//        (SpecifiedLearningCourseDetailsActivity.this).getWindow().setAttributes(lp);
//    }
    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        exitAndSave();
    }





    @Override
    protected void onPause() {
        super.onPause();
        if(sensorManager!=null){
            sensorManager.unregisterListener(sensorEventListener);
        }

//        JZVideoPlayer jzvd = JZVideoPlayerManager.getCurrentJzvd();
//         if(jzvd!=null)
//         {
//            jzvd.onStatePause();
//            JZMediaManager.pause();//暂停
//
//         }else{
//
//                 JZVideoPlayer.releaseAllVideos();
//
//     }

        Jzvd.resetAllVideos();


        /**
         * 记得释放camera，方便其他应用调用
         */
        releaseCamera();
    }



    @Override
    public void onStart() {
        super.onStart();
        if (this.checkCameraHardware(this) && (mCamera == null)) {
            // 打开camera
            mCamera = getCamera();
            if (mHolder != null) {
                setStartPreview(mCamera, mHolder);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //摄像头
        int cameraCount = 1;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();// 得到摄像头的个数

        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);// 得到每一个摄像头的信息
            // 现在是后置，变更为前置
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
                /**
                 * 记得释放camera，方便其他应用调用
                 */
                releaseCamera();
                // 打开当前选中的摄像头
                mCamera = Camera.open(i);
                //   mCamera.setDisplayOrientation(90);//旋转度数
                // 通过surfaceview显示取景画面
                setStartPreview(mCamera, mHolder);

            }
        }




    }


    private Camera getCamera() {
        Camera camera = null;
        try {
            camera = Camera.open();
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            camera = null;
            LogUtils.e(TAG, "Camera is not available (in use or does not exist)");
        }
        return camera;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        FileParseUtil.releaseFileView();
        if(mPopWindow != null) {

            mPopWindow.dismiss();
        }
        if(mSorryPopWindow != null) {

            mSorryPopWindow.dismiss();
        }
        if(mProgressDialog != null ){
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
        mHandler.removeCallbacksAndMessages(null);
        mOffHandler.removeCallbacksAndMessages(null);
        EventBus.getDefault().unregister(this);//反注册EventBus
        SharedPreferences sp = getSharedPreferences("CameraSwitchView",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }

    
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        String imgurl = event.getMessage();
        String messageurl = event.getMessageurl();
        boolean isphoto = event.isIsphoto();
        int code = event.getCode();
        String msg=event.getMsg();
        int faceRecgMark = event.getFaceRecgMark();
        
        if(faceRecgMark==1 || faceRecgMark==2){ //人脸识别
            if (isphoto){
                show_camera_iv.setWillNotDraw(false);
                show_camera_iv.setContentDescription(messageurl);
                Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(messageurl);
                show_camera_iv.setImageBitmap(bitmapByUrl);
                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("imgurl", imgurl);
                edit.commit();
                Toasty.success(this, "人脸识别成功！", Toast.LENGTH_SHORT, true).show();
            }else{
                show_camera_iv.setImageResource(R.mipmap.tongming);
                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("imgurl", "");
                edit.commit();

                if (code == 1) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    View view = View
                            .inflate(IllegallearningCourseDetailsActivity.this, R.layout.diolog_learn_layout, null);
                    TextView tv_message = (TextView) view
                            .findViewById(R.id.message);//输入内容
                    tv_message.setText("非常抱歉，您还没有上传个人头像，我们无法对您对你进行人脸识别。");
                    TextView btn_sure = (TextView) view.findViewById(R.id.positiveButton);
                    TextView btn_cancel = (TextView) view.findViewById(R.id.negativeButton);
                    btn_cancel.setVisibility(View.GONE);
                    btn_sure.setText("上传头像");
                    final AlertDialog dialog = builder.create();
                    dialog.show();
                    dialog.getWindow().setContentView(view);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.setCancelable(false);
                    btn_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            timer1.cancel();
                            timerTask = null;
                            timer1 = null;
                            LoginUserBean userInfo = UserManger.getUserInfo();
                            String userId = userInfo.getData().getUserId();
                            SharedPreferences sp1 = getSharedPreferences("IllegallearningCourseDetailsActivity" + userId,
                                    Context.MODE_PRIVATE);
                            SharedPreferences.Editor edit = sp1.edit();
                            int otcSn1 = sp1.getInt("otcSn", 0);
                            int learnsn = sp1.getInt("learnsn", 0);
                            edit.remove("imgurl" + otcSn1 + learnsn);
                            edit.remove("format" + otcSn1 + learnsn);
                            edit.remove("firsttime" + otcSn1);
                            edit.remove("num" + otcSn1);
                            edit.remove("accessAudioUrl" + otcSn1 + learnsn);
                            edit.remove("intfirsttime" + otcSn1);
                            edit.commit();
                            finish();
                        }
                    });
                } else if (code == 2) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    View view = View
                            .inflate(IllegallearningCourseDetailsActivity.this, R.layout.diolog_learn_layout, null);
                    TextView tv_message = (TextView) view
                            .findViewById(R.id.message);//输入内容
                    tv_message.setText("非常抱歉。系统正在进行维护，请您稍后再进行学习。");
                    TextView btn_sure = (TextView) view.findViewById(R.id.positiveButton);
                    TextView btn_cancel = (TextView) view.findViewById(R.id.negativeButton);
                    btn_cancel.setVisibility(View.GONE);
                    btn_sure.setText("确定");
                    final AlertDialog dialog = builder.create();
                    dialog.show();
                    dialog.getWindow().setContentView(view);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.setCancelable(false);
                    btn_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            timer1.cancel();
                            timerTask = null;
                            timer1 = null;
                            LoginUserBean userInfo = UserManger.getUserInfo();
                            String userId = userInfo.getData().getUserId();
                            SharedPreferences sp1 = getSharedPreferences("IllegallearningCourseDetailsActivity" + userId,
                                    Context.MODE_PRIVATE);
                            SharedPreferences.Editor edit = sp1.edit();
                            int otcSn1 = sp1.getInt("otcSn", 0);
                            int learnsn = sp1.getInt("learnsn", 0);
                            edit.remove("imgurl" + otcSn1 + learnsn);
                            edit.remove("format" + otcSn1 + learnsn);
                            edit.remove("firsttime" + otcSn1);
                            edit.remove("num" + otcSn1);
                            edit.remove("accessAudioUrl" + otcSn1 + learnsn);
                            edit.remove("intfirsttime" + otcSn1);
                            //      edit.remove("tag" + otcSn1);
                            edit.commit();
                            finish();
                        }
                    });
                } else if (code == 3) {
                    timerTask.cancel();
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    View view = View
                            .inflate(IllegallearningCourseDetailsActivity.this, R.layout.diolog_learn_person_layout, null);
                    TextView btn_sure = (TextView) view.findViewById(R.id.positiveButton);
                    TextView btn_cancel = (TextView) view.findViewById(R.id.negativeButton);
                    TextView btn_title = (TextView) view.findViewById(R.id.title);
                    TextView btn_message = (TextView) view.findViewById(R.id.message);
                    btn_title.setVisibility(View.VISIBLE);
                    btn_cancel.setText("我的头像");
                    btn_message.setText("请确保拍照面部完整，五官清晰，如您多次人脸失败，请在“我的头像”中检查您的个人头像是否正常且且清晰。");
                    final AlertDialog dialog = builder.create();
                    dialog.show();
                    dialog.getWindow().setContentView(view);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.setCancelable(false);
                    btn_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            LoginUserBean userInfo = UserManger.getUserInfo();
                            String userId = userInfo.getData().getUserId();
                            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity", Context.MODE_PRIVATE);
                            String firsttime = sp.getString("firsttime", "");//第一次抓拍时间
                            String firsttimesub = firsttime.substring(3, 8);//截取字符串00:00:00变成00:00
                            Bundle bundle = new Bundle();
                            bundle.putInt("uvtSn",sn);
                            bundle.putString("snapTime", firsttimesub);
                            bundle.putString("userId", userId);
                            startActivityForResult(TakePhotoIllegallearningActivity.class, bundle, 0);
                        }
                    });
                    btn_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            showTakePhotoPopupWindow();
                        }
                    });
                }else {
                    timerTask.cancel();
                    View view = View.inflate(IllegallearningCourseDetailsActivity.this, R.layout.diolog_learn_person_layout, null);
                    TextView btn_sure = (TextView) view.findViewById(R.id.positiveButton);
                    TextView btn_cancel = (TextView) view.findViewById(R.id.negativeButton);
                    TextView btn_title = (TextView) view.findViewById(R.id.title);
                    TextView btn_message = (TextView) view.findViewById(R.id.message);
                    btn_title.setVisibility(View.VISIBLE);
                    btn_cancel.setText("我的头像");
                    btn_message.setText(msg);

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    final AlertDialog dialog = builder.create();
                    dialog.show();
                    dialog.getWindow().setContentView(view);
                    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog.setCancelable(false);
                    btn_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            LoginUserBean userInfo = UserManger.getUserInfo();
                            String userId = userInfo.getData().getUserId();
                            SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity", Context.MODE_PRIVATE);
                            String firsttime = sp.getString("firsttime", "");//第一次抓拍时间
                            String firsttimesub = firsttime.substring(3, 8);//截取字符串00:00:00变成00:00
                            Bundle bundle = new Bundle();
                            bundle.putString("snapTime", firsttimesub);
                            bundle.putInt("uvtSn",sn);
                            bundle.putString("userId", userId);
                            startActivityForResult(TakePhotoIllegallearningActivity.class, bundle, 0);

                        }
                    });
                    btn_cancel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                            showTakePhotoPopupWindow();
                        }
                    });
                }
            }
        }else{ //非人脸识别
            if (isphoto){
                show_camera_iv.setWillNotDraw(false);
                show_camera_iv.setContentDescription(messageurl);
                Bitmap bitmapByUrl = HelpUtil.getBitmapByUrl(messageurl);
                show_camera_iv.setImageBitmap(bitmapByUrl);
                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("imgurl", imgurl);
                edit.commit();
            }else{
                show_camera_iv.setImageResource(R.mipmap.tongming);
                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("imgurl", "");
                edit.commit();
                Toast.makeText(IllegallearningCourseDetailsActivity.this,"照片上传失败",Toast.LENGTH_LONG).show();
            }
        }

    }
    /**
     * 释放mCamera
     */
    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();// 停掉原来摄像头的预览
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        setStartPreview(mCamera, mHolder);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null) {
            // preview surface does not exist
            return;
        }
        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
        }

        setStartPreview(mCamera, mHolder);

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // 当surfaceview关闭时，关闭预览并释放资源
        /**
         * 记得释放camera，方便其他应用调用
         */
        releaseCamera();
        holder = null;
        surfaceSv = null;
    }



    /**
     * Check if this device has a camera
     */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }
    /*****
     * 接受第二个Activity返回的数据时调用
     *
     * ****/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        String url = data.getStringExtra("url");
        // 根据返回码的不同，设置参数
        if (requestCode == 0) {
            if(resultCode==1) {
                if (url != null && !TextUtils.isEmpty(url)) {
                    SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                            Context.MODE_PRIVATE);
                    String stringTime = sp.getString("format", "");
                    int index1 = stringTime.indexOf(":");
                    int index2 = stringTime.indexOf(":", index1 + 1);
                    int hh = Integer.parseInt(stringTime.substring(0, index1));
                    int mi = Integer.parseInt(stringTime.substring(index1 + 1, index2));
                    int ss = Integer.parseInt(stringTime.substring(index2 + 1));
                    int  formatTurnSecond = hh * 60 * 60 + mi * 60 + ss;
                    subformatTurnSecond = formatTurnSecond + 1;//处理拍照时延迟1秒
                    String stringTime1 = getStringTime(subformatTurnSecond);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("format", stringTime1);
                    edit.commit();

                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //在子线程中执行任务，执行完成或需要通知UI线程时调用以下方法
                            mHandler.sendEmptyMessage(0);
                        }
                    });
                    thread.start();
                }

            }

        }
    }


    /**
     * 设置camera显示取景画面,并预览
     *
     * @param camera
     */
    private void setStartPreview(Camera camera, SurfaceHolder holder) {
        try {
            camera.setPreviewDisplay(holder);
            //开始预览
            camera.setDisplayOrientation(90);
            camera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }


    private void showTakePhotoPopupWindow() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = View
                .inflate(IllegallearningCourseDetailsActivity.this, R.layout.diolog_photo_layout, null);
        LoginUserBean userInfo = UserManger.getUserInfo();
        String userId = userInfo.getData().getUserId();
        SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity" + userId,
                Context.MODE_PRIVATE);
        String photoUrl = sp.getString("photoUrl", "");
        ImageView img_photo = (ImageView) view.findViewById(R.id.img_photo2);
        if (!photoUrl.equals("")) {
            Picasso.with(IllegallearningCourseDetailsActivity.this).load(Uri.parse(photoUrl)).placeholder(R.mipmap.my_head).into(img_photo);//加载图片
        }
        TextView btn_PositiveButton = (TextView) view.findViewById(R.id.tv_photo6);//拍照
        TextView btn_NegativeButton = (TextView) view.findViewById(R.id.tv_photo5);//手机获取照片
        final AlertDialog dialog = builder.create();
        dialog.show();
        dialog.getWindow().setContentView(view);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setCancelable(false);
        btn_PositiveButton.setOnClickListener(new View.OnClickListener() {//拍照
            @Override
            public void onClick(View view) {
                LoginUserBean userInfo = UserManger.getUserInfo();
                String userId = userInfo.getData().getUserId();
                SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity" + userId,
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                int otcSn = sp.getInt("otcSn", 0);
                edit.putInt("tag" + otcSn, 1);
                edit.commit();
                startActivityForResult(TakePersonPictureActivity.class, null, 1);
                dialog.dismiss();
            }
        });
    }

    private void showAlertDialog(SuperFileView2 superFileView2, String url) {
        //1、使用Dialog、设置style
        //2、设置布局

        View contentView = LayoutInflater.from(IllegallearningCourseDetailsActivity.this).inflate(R.layout.dialog_circle, null);
        mDownloadPopWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);

        mDownloadPopWindow.setContentView(contentView);
        mDownloadPopWindow.setFocusable(false);
        mDownloadPopWindow.setOutsideTouchable(false);
        mDownloadPopWindow.showAtLocation(contentView, Gravity.CENTER, 0, 0);


        CircularProgressView circularProgressView = contentView.findViewById(R.id.circleProgress);
        TextView textView = contentView.findViewById(R.id.progressTxt);
        TextView textView1 = contentView.findViewById(R.id.hintTxt);

        jumpingBeans2 = JumpingBeans.with(textView1)
                .makeTextJump(0, textView1.getText().length())
                .setIsWave(true)
                .setLoopDuration(3000)
                .build();

        downLoadFromNet(url, superFileView2, circularProgressView, textView);
    }

    private void downLoadFromNet(final String url, final SuperFileView2 superFileView, CircularProgressView circularProgressView, TextView tv1) {
        //showLoadingDialog("文件下载中...");
        //1.网络下载、存储路径、
        File cacheFile = FileParseUtil.getCacheFile(url);
        if (cacheFile.exists()) {
            if (cacheFile.length() <= 0) {
                cacheFile.delete();
                return;
            }
        }

        OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).build();
        Request request = new Request.Builder().get().url(url).build();
        okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //请求成功,从服务器的响应对象中获取apk,流(服务器 输入流(提供数据)  本地 输出流(写入文件))
                ResponseBody body = response.body();
                //告知progressDialog总进度,不变
                //progressDialog.setMax((int) body.contentLength());
                final int allLength = (int) body.contentLength();
                //inputStream就是服务器把需要下载的apk以流的形式提供给客户端
                InputStream inputStream = body.byteStream();

                String fileName = url.substring(url.lastIndexOf("/"));
                String directory = Environment.getExternalStoragePublicDirectory
                        (Environment.DIRECTORY_DOWNLOADS).getPath();
                //File file = new File(directory+fileName);

                File file = FileParseUtil.getCacheFile(url);
                FileOutputStream fos = new FileOutputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                int temp = 0;//用于记录目前下载的到的位置
                while ((len = inputStream.read(bytes)) != -1) {
                    //将读过的数据写入文件中
                    fos.write(bytes, 0, len);
                    //告知progressDialog在下载过程中的当前进度
                    temp += len;
                    //将当前的下载位置,设置给progressDialog
                    //progressDialog.setProgress(temp);
                    //没下载一段数据,睡眠一段时间

                    int progress = (int) (temp * 100.0 / allLength);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            circularProgressView.setProgress(progress);
                            tv1.setText(progress + "%");
                        }
                    });

                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //2.ACache记录文件的有效期
                        mDownloadPopWindow.dismiss();
                        superFileView.displayFile(file);
                    }
                });
            }
        });
    }


    private void userViolationTCourseFinish(int sn,int readLength,int finishMark){
        new Login().userViolationTCourseFinish(sn,readLength,finishMark,IllegallearningCourseDetailsActivity.this,1);
    }


    private void exitAndSave(){
        SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                Context.MODE_PRIVATE);
        String format = sp.getString("format", "");
        String imgurl = sp.getString("imgurl", "");
        int num = sp.getInt("num", 0);
        String[] splitformat = format.split(":");
        String format1 = splitformat[0];
        String format2 = splitformat[1];
        String format3 = splitformat[2];
        int iformat1 = Integer.valueOf(format1);//转int
        int iformat2 = Integer.valueOf(format2);//转int
        int iformat3 = Integer.valueOf(format3);//转int
        int formattime = iformat1 * 3600 + iformat2 * 60 + iformat3 * 1;

        if(formattime>=60){
            TiShiDialog.Builder builder = new TiShiDialog.Builder(this);
            builder.setMessage("您的学习进度已保存，下次进入将继续本课程的学习");
            builder.setTitle("提示:");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                    mProgressDialog = new ProgressDialog(IllegallearningCourseDetailsActivity.this,ProgressDialog.THEME_HOLO_DARK);
                    mProgressDialog.setMessage("保存中...");
                    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.show();
                    userViolationTCourseFinish(sn,formattime,0);

//                    if(formattime<num){
//                        mProgressDialog = new ProgressDialog(IllegallearningCourseDetailsActivity.this,ProgressDialog.THEME_HOLO_DARK);
//                        mProgressDialog.setMessage("保存中...");
//                        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//                        mProgressDialog.setCancelable(false);
//                        mProgressDialog.show();
//                        userViolationTCourseFinish(sn,formattime,0);
//                    }else{
//                        if(imgurl.equals(""))
//                        {
//                            timerTask.cancel();
//                            //  tv_pause.setVisibility(View.GONE);
//                            initDialog2();
//                            return;
//                        }
//                        mProgressDialog = new ProgressDialog(IllegallearningCourseDetailsActivity.this,ProgressDialog.THEME_HOLO_DARK);
//                        mProgressDialog.setMessage("保存中...");
//                        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//                        mProgressDialog.setCancelable(false);
//                        mProgressDialog.show();
//                        userViolationTCourseFinish(sn,num,1);
//                    }

                }
            });
            builder.setNegativeButton("取消",
                    new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();
        }else{
            TiShiDialog.Builder builder = new TiShiDialog.Builder(this);
            builder.setMessage("您本次学习未满一分钟，无法保存学习进度，退出后将重新学习本课程。");
            builder.setTitle("提示:");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    SharedPreferences sp = getSharedPreferences("IllegallearningCourseDetailsActivity",
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    edit.clear();
                    edit.commit();
                    timerTask.cancel();
                    timer1.cancel();
                    timerTask=null;
                    timer1=null;
                    dialog.dismiss();
                    finish();

                }
            });
            builder.setNegativeButton("取消",
                    new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create().show();
        }


    }
}